package com.gaattc.controller.admin;

import com.gaattc.model.Admin;
import com.gaattc.model.Result;
import com.gaattc.model.bo.AdminLoginBO;
import com.gaattc.model.bo.ChangePwdBO;
import com.gaattc.model.vo.AdminLoginVO;
import com.gaattc.service.AdminService;
import com.gaattc.service.AdminServiceImpl;
import com.gaattc.utils.HttpUtils;
import com.google.gson.Gson;
import javafx.scene.control.TextFormatter;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/api/admin/admin/*")
public class AdminServlet extends HttpServlet {

    private AdminService adminService = new AdminServiceImpl();

    private Gson gson = new Gson();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //  /api/admin/admin/login
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/admin/admin/", "");
        //根据请求资源分发
        if("login".equals(action)){
            login(request, response);
        } else if("addAdminss".equals(action)) {
            addAdmins(request, response);
        } else if("updateAdminss".equals(action)) {
            updateAdminss(request, response);
        } else if("getSearchAdmins".equals(action)) {
            getSearchAdmins(request, response);
        } else  if("changePwd".equals(action)) {
            changePwd(request, response);
        } else if("logoutAdmin".equals(action)) {
            logoutAdmin(request, response);
        }
    }

    /**
     * 注销登录账户
     * @param request req
     * @param response resp
     * @throws IOException io
     */
    private void logoutAdmin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().invalidate();
        response.getWriter().println(gson.toJson(Result.ok()));
    }

    /**
     * 修改管理员密码
     * @param request req
     * @param response resp
     */
    private void changePwd(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        ChangePwdBO changePwdBO = gson.fromJson(requestBody, ChangePwdBO.class);
        //检查合法性
        if(!changePwdBO.getNewPwd().equals(changePwdBO.getConfirmPwd())) {
            response.getWriter().println(gson.toJson(Result.error("新密码不一致")));
            return;
        }
        if(changePwdBO.getNewPwd().equals(changePwdBO.getOldPwd())) {
            response.getWriter().println(gson.toJson(Result.error("新旧密码相同")));
            return;
        }
        //检查无误再交给service执行查询修改
        int code = adminService.changePwd(changePwdBO);
        if(code == 1) {
            response.getWriter().println(gson.toJson(Result.ok()));
        } else if(code == 10000) {
            response.getWriter().println(gson.toJson(Result.error("修改失败")));
        }
    }

    /**
     * 搜索符合条件的管理员
     * @param request req
     * @param response resp
     */
    private void getSearchAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        Admin admin = gson.fromJson(requestBody, Admin.class);
        List<Admin> result = adminService.getSearchAdmins(admin);
        response.getWriter().println(gson.toJson(Result.ok(result)));
    }

    /**
     * 修改管理员
     * @param request  req
     * @param response resp
     */
    private void updateAdminss(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        Admin admin = gson.fromJson(requestBody, Admin.class);
        //判断是否为空
        if(StringUtils.isEmpty(admin.getEmail()) || StringUtils.isEmpty(admin.getPwd()) || StringUtils.isEmpty(admin.getNickname())){
            response.getWriter().println(gson.toJson(Result.error("参数不能为空")));
            return;
        }
        int code = adminService.updateAdminss(admin);
        if(code == 1) {
            response.getWriter().println(gson.toJson(Result.ok()));
            return;
        }
        response.getWriter().println(gson.toJson(Result.error("邮箱账号已被注册")));
    }

    /**
     * 添加管理员
     * @param request req
     * @param response resp
     */
    private void addAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        Admin admin = gson.fromJson(requestBody, Admin.class);
        //判断是否为空
        if(StringUtils.isEmpty(admin.getEmail()) || StringUtils.isEmpty(admin.getPwd()) || StringUtils.isEmpty(admin.getNickname())){
            response.getWriter().println(gson.toJson(Result.error("参数不能为空")));
            return;
        }
        int code = adminService.addAdmins(admin);
        //添加成功
        if(code == 1) {
            response.getWriter().println(gson.toJson(Result.ok()));
            return;
        }
        //添加失败
        response.getWriter().println(gson.toJson(Result.error("邮箱账号已被注册")));
    }

    /**
     * 管理员登录的业务逻辑
     *  bo  vo  bean
     *  bo:business object
     *  vo:view object
     *  bean:和数据库对应的
     *  一个视图可能有多个model组合而成
     *  vo里面的数据可能是多个bean杂糅在一起的结果 向客户端输出
     *  bo 客户端输入
     *  一个接口中一般会对应三个对象
     *  bo：用来处理客户端的输入
     *  bean：一般和数据库表字段一一对应()
     *  vo:根据实际的情况，页面需要哪些，你构建哪些  jd  我的  order  info （封装）
     * @param request 请求
     * @param response 响应
     */
    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        AdminLoginBO loginBO = gson.fromJson(requestBody, AdminLoginBO.class);
        //判断是否为空 StringUtils
        if(StringUtils.isEmpty(loginBO.getEmail()) || StringUtils.isEmpty(loginBO.getPwd())){
            //返回某个响应结果
            response.getWriter().println(gson.toJson(Result.error("参数不能为空")));
            return;
        }
       int code =  adminService.login(loginBO);
        //返回响应结果
        if(code == 200){
            request.getSession().setAttribute("username",loginBO.getEmail());
            response.getWriter().println(gson.toJson(Result.ok(new AdminLoginVO(loginBO.getEmail(),loginBO.getEmail()))));
            return;
        }
        response.getWriter().println(gson.toJson(Result.error("确认用户名和密码")));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/admin/admin/", "");
        if("allAdmins".equals(action)){
            allAdmins(request, response);
        } else if("getAdminsInfo".equals(action)) {
            getAdminsInfo(request, response);
        } else if("deleteAdmins".equals(action)) {
            deleteAdmin(request, response);
        }
    }

    /**
     * 删除管理员
     * @param request req
     * @param response resp
     */
    private void deleteAdmin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        int code = adminService.deleteAdmins(id);
        System.out.println(code);
        if(code == 1) {
            response.getWriter().println(gson.toJson(Result.ok()));
            return;
        }
        response.getWriter().println(gson.toJson(Result.error("删除失败")));
    }

    /**
     * 获取要修改的管理员信息
     * @param request req
     * @param response resp
     */
    private void getAdminsInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        Admin adminInfo = adminService.getAdminsInfo(id);
        response.getWriter().println(gson.toJson(Result.ok(adminInfo)));
    }

    /**
     * 不用获取请求参数，直接取查询全部admin信息，然后返回
     * 返回的数据格式：参考公网服务器上面的报文
     * @param request 请求
     * @param response 响应
     */
    private void allAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Admin> adminList = adminService.allAdmins();
        response.getWriter().println(gson.toJson(Result.ok(adminList)));
    }
}
